/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.controller.admin;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.request.admin.ServiceRequestMessage;
import cn.easyplatform.messages.vos.ListVo;
import cn.easyplatform.messages.vos.TaskRuntimeVo;
import cn.easyplatform.messages.vos.admin.ServiceVo;
import cn.easyplatform.spi.service.AdminService;
import cn.easyplatform.type.FieldVo;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.ServiceType;
import cn.easyplatform.utils.SerializationUtils;
import cn.easyplatform.web.contexts.Contexts;
import cn.easyplatform.web.dialog.MessageBox;
import cn.easyplatform.web.layout.debug.AbstractDebugPanelBuilder;
import cn.easyplatform.web.layout.debug.FieldComprator;
import cn.easyplatform.web.listener.MessageEventListener;
import cn.easyplatform.web.log.LogManager;
import cn.easyplatform.web.message.entity.Message;
import cn.easyplatform.web.service.ServiceLocator;
import org.apache.commons.lang3.ArrayUtils;
import org.zkoss.util.media.AMedia;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zkmax.zul.Filedownload;
import org.zkoss.zul.*;

import java.util.*;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/11/7 15:37
 * @Modified By:
 */
public class WorkController extends SelectorComposer<Window> implements EventListener<Event> {

    private String targetId;

    @Wire("group#detail")
    private Group detail;

    @Wire("group#fields")
    private Group fields;

    @Wire("group#variables")
    private Group variables;

    @Wire("group#lists")
    private Group lists;

    @Wire("listbox#works")
    private Listbox works;

    @Override
    public void doAfterCompose(Window win) throws Exception {
        super.doAfterCompose(win);
        ServiceVo vo = (ServiceVo) Executions.getCurrent().getArg().get("s");
        targetId = vo.getId();
        win.setTitle(Labels.getLabel("admin.user.wf") + " : " + vo.getId() + " (" + vo.getName() + ")");
        if (!load())
            win.detach();
    }

    /**
     * 加载运行信息
     *
     * @return
     */
    private boolean load() {
        AdminService as = ServiceLocator.lookup(AdminService.class);
        IResponseMessage<?> resp = as.getService(new ServiceRequestMessage(new ServiceVo(targetId, ServiceType.USER)));
        if (resp.isSuccess()) {
            if (resp.getBody() != null) {
                List<TaskRuntimeVo> data = (List<TaskRuntimeVo>) resp.getBody();
                for (TaskRuntimeVo tv : data) {
                    Listitem li = new Listitem();
                    li.appendChild(new Listcell((String) tv.getSystemVars().get("801")));
                    li.appendChild(new Listcell((String) tv.getSystemVars().get("802")));
                    li.appendChild(new Listcell((String) tv.getSystemVars().get("800")));
                    li.setValue(tv);
                    works.appendChild(li);
                }
                works.setSelectedIndex(0);
                onSelect();
            }
        } else
            MessageBox.showMessage(resp);
        return resp.isSuccess();
    }

    @Listen("onClick=#refresh")
    public void onRefresh() {
        works.getItems().clear();
        load();
    }

    @Listen("onSelect=#works")
    public void onSelect() {
        TaskRuntimeVo tv = works.getSelectedItem().getValue();
        Component parent = detail.getParent();
        parent.getChildren().clear();
        parent.appendChild(detail);
        parent.appendChild(fields);
        parent.appendChild(variables);
        parent.appendChild(lists);
        fields.setOpen(false);
        variables.setOpen(false);
        lists.setOpen(false);
        Iterator<Map.Entry<String, Object>> itr = new TreeMap<>(
                tv.getSystemVars()).entrySet().iterator();
        while (itr.hasNext()) {
            Map.Entry<String, Object> entry = itr.next();
            Row row = new Row();
            createSystemRow(entry, row);
            detail.getParent().insertBefore(row, fields);
        }
        if (tv.getFieldVars() != null) {
            Collections.sort(tv.getFieldVars(), new FieldComprator());
            Iterator<FieldVo> it = tv.getFieldVars().iterator();
            while (it.hasNext())
                createFieldRow(fields, variables, it.next());
        }
        if (tv.getUserVars() != null) {
            Collections.sort(tv.getUserVars(), new FieldComprator());
            Iterator<FieldVo> it = tv.getUserVars().iterator();
            while (it.hasNext())
                createFieldRow(variables, lists, it.next());
        }
        if (tv.getListVars() != null) {
            for (ListVo lv : tv.getListVars()) {
                Row row = new Row();
                Label label = new Label(lv.getId());
                row.appendChild(label);
                label = new Label(lv.getType());
                row.appendChild(label);
                lists.getParent().appendChild(row);
            }
        }
    }

    private void createFieldRow(Group group, Group ref, FieldVo fv) {
        Row row = new Row();
        row.appendChild(new Label(fv.getName()));
        Label label = new Label();
        if (fv.getValue() != null) {
            Object val = fv.getValue();
            if (val instanceof byte[]) {
                try {
                    val = SerializationUtils
                            .deserialize((byte[]) fv.getValue());
                } catch (Exception ex) {
                }
            }
            if (val instanceof Object[])
                label.setValue(ArrayUtils.toString(val));
            else
                label.setValue(val.toString());
        }
        row.appendChild(label);
        group.getParent().insertBefore(row, ref);
    }

    private void createSystemRow(Map.Entry<String, Object> entry, Row row) {
        String desp = AbstractDebugPanelBuilder.systemProperties.get(entry.getKey());
        if (desp == null)
            desp = "";
        else
            desp = "-" + desp;
        Label label = new Label(entry.getKey() + desp);
        row.appendChild(label);
        if (entry.getValue() != null) {
            if (AbstractDebugPanelBuilder.sourceViews.contains(entry.getKey())) {
                A a = new A(entry.getValue().toString());
                a.setTooltiptext(entry.getValue().toString());
                a.setParent(row);
                a.addEventListener(Events.ON_CLICK, this);
                a.setAttribute("value", entry.getKey());
                row.appendChild(a);
            } else {
                label = new Label(entry.getValue().toString());
                label.setTooltiptext(entry.getValue().toString());
                row.appendChild(label);
            }
        } else
            row.appendChild(new Label());
    }

    @Override
    public void onEvent(Event event) throws Exception {

    }
}
